﻿using DeviceMaintainGIS.Entity;
using DeviceMaintainGIS.Model.LocaInfo;
using DeviceMaintainGIS.Model.LocaManagerTab;
using DeviceMaintainGIS.Model.LocaTypeTab;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using System.Web.Script.Serialization;

namespace AchieveManageWeb.Controllers
{
    public class LocaController : Controller
    {
        //
        // GET: /Loca/

        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 基站添加
        /// </summary>
        /// <returns></returns>
        public ActionResult LocaAdd()
        {
            using (CYOADBEntities Entities = new CYOADBEntities())
            {
                var linq = from a in Entities.LocaType_Tab
                           select new LocaTypeModel
                           {
                               LocaTypeId = a.LocaTypeId,
                               LocaTyp = a.LocaTyp
                           };
                List<LocaTypeModel> list = linq.ToList();
                ViewBag.LocaTypeList = list;
            };
            return View();
        }

        /// <summary>
        /// 基站编辑
        /// </summary>
        /// <returns></returns>
        public ActionResult LocaEdit()
        {
            LocaInfoModel lin = new LocaInfoModel();
            string LocaId = Request["LocaId"];

            using (CYOADBEntities Entities = new CYOADBEntities())
            {
                var linq = from a in Entities.LocaType_Tab
                           select new LocaTypeModel
                           {
                               LocaTypeId = a.LocaTypeId,
                               LocaTyp = a.LocaTyp
                           };
                List<LocaTypeModel> list = linq.ToList();
                ViewBag.LocaTypeList = list;

                var linqs = from a in Entities.LocaInfo_Tab.Where(i => i.LocaId == LocaId)
                            select new LocaInfoModel
                            {
                                LocaId = a.LocaId,
                                LocaName = a.LocaName,
                                LocaTypeId = a.LocaTypeId,
                                LocaHigh = a.LocaHigh,
                                Describe = a.Describe,
                                Link = a.Link,
                                PowerMode = a.PowerMode,
                                District = a.District,
                                Town = a.Town,
                                Longitude = a.Longitude,
                                Latitude = a.Latitude,
                                Altitude = a.Altitude,
                                NaviLongitude = a.NaviLongitude,
                                NaviLatitude = a.NaviLatitude,
                                StopLongitude = a.StopLongitude,
                                StopLatitude = a.StopLatitude,
                                Village = a.Village,
                                Remark = a.Remark,
                            };
                lin = linqs.FirstOrDefault();
            };

            return View(lin);
        }
        /// <summary>
        /// 基站负责人信息添加
        /// </summary>
        /// <returns></returns>
        public ActionResult LocaManagerAdd()
        {
            return View();
        }

        public ActionResult LocaManagerIsLeader(string LocaId)
        {
            int intIsLeader = 0;
            using (CYOADBEntities Entities = new CYOADBEntities())
            {
                //获取表中是否设置了主要负责人
                intIsLeader = Entities.LocaManager_Tab.Where(i => i.IsLeader == true && i.LocaId == LocaId).ToList().Count;

            };
            return Content("{\"msg\":\"" + intIsLeader + "\",\"success\":true}");
        }

        /// <summary>
        /// 添加基站信息
        /// </summary>
        /// <returns></returns>
        public ActionResult LocaInfoAdd(LocaInfoModel lim)
        {
            try
            {
                //IEnumerable<LocaInfo_Tab> lits = new IEnumerable<LocaInfo_Tab>();
                string newID = Guid.NewGuid().ToString();
                LocaInfo_Tab lit = new LocaInfo_Tab();
                lit.LocaId = newID;
                lit.LocaName = lim.LocaName;
                lit.LocaTypeId = lim.LocaTypeId;
                lit.LocaHigh = lim.LocaHigh;
                lit.Describe = lim.Describe;
                lit.Link = lim.Link;
                lit.PowerMode = lim.PowerMode;
                lit.District = lim.District;
                lit.Town = lim.Town;
                lit.Longitude = lim.Longitude;
                lit.Latitude = lim.Latitude;
                lit.Altitude = lim.Altitude;
                lit.NaviLongitude = lim.NaviLongitude;
                lit.NaviLatitude = lim.NaviLatitude;
                lit.StopLongitude = lim.StopLongitude;
                lit.StopLatitude = lim.StopLatitude;
                lit.Village = lim.Village;
                lit.Remark = lim.Remark;
                lit.AddTime = System.DateTime.Now;
                int code = 0;
                using (CYOADBEntities Entities = new CYOADBEntities())
                {
                    int tmpCount = Entities.LocaInfo_Tab.Where(i => i.LocaName == lim.LocaName).Count();
                    if (tmpCount > 0)
                    {
                        return Content("{\"msg\":\"添加失败！基站名称已存在！\",\"success\":false}");
                    }
                    Entities.LocaInfo_Tab.Add(lit);
                    Entities.Entry<LocaInfo_Tab>(lit).State = System.Data.Entity.EntityState.Added;
                    code = Entities.SaveChanges();
                };
                if (code > 0)
                {
                    //if (!string.IsNullOrEmpty(lim.LocaManagerTablJson))
                    //{
                    //    JavaScriptSerializer jsonSerialize = new JavaScriptSerializer();
                    //    List<LocaManagerModel> lis = jsonSerialize.Deserialize<List<LocaManagerModel>>(lim.LocaManagerTablJson);
                    //    using (CYOADBEntities Entities = new CYOADBEntities())
                    //    {
                    //        foreach (LocaManagerModel li in lis)
                    //        {
                    //            LocaManager_Tab ltt = new LocaManager_Tab();
                    //            ltt.IsLeader = li.IsLeader;
                    //            ltt.LocaId = newID;
                    //            ltt.LocaManagerId = Guid.NewGuid().ToString();
                    //            ltt.LocaManager = li.LocaManager;
                    //            ltt.Tel = li.Tel;
                    //            Entities.LocaManager_Tab.Add(ltt);
                    //            Entities.Entry<LocaManager_Tab>(ltt).State = System.Data.Entity.EntityState.Added;
                    //        }
                    //        code = Entities.SaveChanges();
                    //    }
                    //}
                    return Content("{\"msg\":\"添加成功！\",\"success\":true}");
                }
                else
                {
                    return Content("{\"msg\":\"添加失败！入库失败\",\"success\":false}");
                }
            }
            catch (Exception ex)
            {
                return Content("{\"msg\":\"添加失败," + ex.Message + "\",\"success\":false}");
            }
        }

        /// <summary>
        /// 编辑基站信息
        /// </summary>
        /// <returns></returns>
        public ActionResult LocaInfoEdit(LocaInfoModel lim)
        {
            try
            {
                int code = 0;
                using (CYOADBEntities Entities = new CYOADBEntities())
                {


                    LocaInfo_Tab lit = Entities.LocaInfo_Tab.Where(i => i.LocaId == lim.LocaId).FirstOrDefault();
                    if (lit == null)
                    {
                        return Content("{\"msg\":\"修改失败！未查询到此基站\",\"success\":false}");
                    }
                    int tmpCount = Entities.LocaInfo_Tab.Where(i => i.LocaName == lim.LocaName).Count();
                    if (tmpCount > 1)
                    {
                        return Content("{\"msg\":\"添加失败！基站名称已存在！\",\"success\":false}");
                    }
                    lit.LocaName = lim.LocaName;
                    lit.LocaTypeId = lim.LocaTypeId;
                    lit.LocaHigh = lim.LocaHigh;
                    lit.Describe = lim.Describe;
                    lit.Link = lim.Link;
                    lit.PowerMode = lim.PowerMode;
                    lit.District = lim.District;
                    lit.Town = lim.Town;
                    lit.Longitude = lim.Longitude;
                    lit.Latitude = lim.Latitude;
                    lit.Altitude = lim.Altitude;
                    lit.NaviLongitude = lim.NaviLongitude;
                    lit.NaviLatitude = lim.NaviLatitude;
                    lit.StopLongitude = lim.StopLongitude;
                    lit.StopLatitude = lim.StopLatitude;
                    lit.Village = lim.Village;
                    lit.Remark = lim.Remark;


                    Entities.LocaInfo_Tab.Add(lit);
                    Entities.Entry<LocaInfo_Tab>(lit).State = System.Data.Entity.EntityState.Modified;
                    code = Entities.SaveChanges();
                };
                if (code > 0)
                {

                    return Content("{\"msg\":\"修改成功！\",\"success\":true}");
                }
                else
                {
                    return Content("{\"msg\":\"修改失败！入库失败\",\"success\":false}");
                }
            }
            catch (Exception ex)
            {
                return Content("{\"msg\":\"修改失败," + ex.Message + "\",\"success\":false}");
            }
        }
        /// <summary>
        /// 添加基站负责人信息
        /// </summary>
        /// <returns></returns>
        public ActionResult LocaManagerInfoAdd(LocaManagerModel lmm)
        {
            string newID = Guid.NewGuid().ToString();
            LocaManager_Tab lit = new LocaManager_Tab();
            lit.LocaManagerId = newID;
            lit.LocaId = lmm.LocaId;
            lit.IsLeader = lmm.IsLeader;
            lit.LocaManager = lmm.LocaManager;
            lit.Tel = lmm.Tel;
            int code = 0;
            using (CYOADBEntities Entities = new CYOADBEntities())
            {

                if (lit.IsLeader)
                {
                    LocaManager_Tab lmt = Entities.LocaManager_Tab.Where(i => i.LocaId == lmm.LocaId && i.IsLeader == true).FirstOrDefault();
                    if (lmt != null)
                    {
                        lmt.IsLeader = false;
                        Entities.LocaManager_Tab.Add(lmt);
                        Entities.Entry<LocaManager_Tab>(lmt).State = System.Data.Entity.EntityState.Modified;
                    }
                }
                Entities.LocaManager_Tab.Add(lit);
                Entities.Entry<LocaManager_Tab>(lit).State = System.Data.Entity.EntityState.Added;
                code = Entities.SaveChanges();
            }
            if (code > 0)
            {
                return Content("{\"msg\":\"添加成功！\",\"success\":true}");
            }
            else
            {
                return Content("{\"msg\":\"添加失败！入库失败\",\"success\":true}");
            }
        }
        /// <summary>
        /// 根据条件获取基站信息
        /// </summary>
        public ActionResult GetAllLocaInfo()
        {
            try
            {
                //首先获取前台传递过来的参数
                int pageindex = Request["page"] == null ? 1 : Convert.ToInt32(Request["page"]);
                int pagesize = Request["rows"] == null ? 10 : Convert.ToInt32(Request["rows"]);

                string selLocaName = Request["selLocaName"] == null ? "" : Request["selLocaName"].ToString();
                string selDistrict = Request["selDistrict"] == null ? "" : Request["selDistrict"].ToString();
                string selTown = Request["selTown"] == null ? "" : Request["selTown"].ToString();
                string strJson;

                int totalCount;   //输出参数
                using (CYOADBEntities Entities = new CYOADBEntities())
                {
                    var linq = from a in Entities.LocaInfo_Tab
                               join f in Entities.LocaType_Tab on a.LocaTypeId equals f.LocaTypeId
                               into tmpLocaType
                               let k = tmpLocaType.FirstOrDefault()
                               select new LocaInfoModel
                               {
                                   LocaId = a.LocaId,
                                   LocaName = a.LocaName,
                                   LocaTypeId = a.LocaTypeId,
                                   LocaTypeName = k == null ? "" : k.LocaTyp,
                                   LocaHigh = a.LocaHigh,
                                   Describe = a.Describe,
                                   Link = a.Link,
                                   PowerMode = a.PowerMode,
                                   District = a.District,
                                   Town = a.Town,
                                   Longitude = a.Longitude,
                                   Latitude = a.Latitude,
                                   Altitude = a.Altitude,
                                   NaviLongitude = a.NaviLongitude,
                                   NaviLatitude = a.NaviLatitude,
                                   StopLongitude = a.StopLongitude,
                                   StopLatitude = a.StopLatitude,
                                   Village = a.Village,
                                   Remark = a.Remark,
                               };
                    if (!string.IsNullOrEmpty(selLocaName))
                    {
                        linq = linq.Where(i => i.LocaName.Contains(selLocaName));
                    }
                    if (!string.IsNullOrEmpty(selDistrict))
                    {
                        linq = linq.Where(i => i.District.Contains(selDistrict));
                    }
                    if (!string.IsNullOrEmpty(selTown))
                    {
                        linq = linq.Where(i => i.Town.Contains(selTown));
                    }

                    totalCount = linq.Count();
                    List<LocaInfoModel> list = linq.OrderBy(i => i.LocaId).Take(pagesize * pageindex).Skip(pagesize * (pageindex - 1)).ToList();

                    JavaScriptSerializer jsonSerialize = new JavaScriptSerializer();
                    strJson = jsonSerialize.Serialize(list);
                }
                var jsonResult = new { total = totalCount.ToString(), rows = strJson };
                return Content("{\"total\": " + totalCount.ToString() + ",\"rows\":" + strJson + "}");
            }
            catch (Exception ee)
            {
                return Content("{\"total\": 0,\"rows\":''}");
            }
        }

        /// <summary>
        /// 根据基站ID获取基站负责人信息
        /// </summary>
        /// <returns></returns>
        public ActionResult GetLocaManagerByLocaId()
        {
            //首先获取前台传递过来的参数
            int pageindex = Request["page"] == null ? 1 : Convert.ToInt32(Request["page"]);
            int pagesize = Request["rows"] == null ? 10 : Convert.ToInt32(Request["rows"]);
            string LocaId = Request["LocaId"];
            string strJson;
            int totalCount;
            using (CYOADBEntities Entities = new CYOADBEntities())
            {
                var linq = from a in Entities.LocaManager_Tab.Where(i => i.LocaId == LocaId)
                           select new LocaManagerModel
                           {
                               LocaManagerId = a.LocaManagerId,
                               LocaManager = a.LocaManager,
                               IsLeader = a.IsLeader,
                               Tel = a.Tel
                           };

                totalCount = linq.Count();
                List<LocaManagerModel> list = linq.OrderByDescending(i => i.IsLeader).Take(pagesize * pageindex).Skip(pagesize * (pageindex - 1)).ToList();

                JavaScriptSerializer jsonSerialize = new JavaScriptSerializer();
                strJson = jsonSerialize.Serialize(list);
            }
            var jsonResult = new { total = totalCount.ToString(), rows = strJson };
            return Content("{\"total\": " + totalCount.ToString() + ",\"rows\":" + strJson + "}");
        }
        /// <summary>
        /// 根据ID删除责任人信息
        /// </summary>
        /// <returns></returns>
        public ActionResult DelLocaManager()
        {
            string LocaManagerId = Request["LocaManagerId"];
            int Code = 0;
            string msg = "";
            using (CYOADBEntities Entities = new CYOADBEntities())
            {
                LocaManager_Tab lmt = Entities.LocaManager_Tab.Where(i => i.LocaManagerId == LocaManagerId).FirstOrDefault();
                if (lmt != null)
                {
                    Entities.LocaManager_Tab.Add(lmt);
                    Entities.Entry<LocaManager_Tab>(lmt).State = System.Data.Entity.EntityState.Deleted;
                    Code = Entities.SaveChanges();
                }
                else
                {
                    Code = -1;
                    msg = "未查询到信息，无法删除";
                }
            }
            if (Code > 0)
            {
                return Content("{\"msg\":\"添加成功！\",\"success\":true}");
            }
            else
            {
                return Content("{\"msg\":\"添加失败！" + msg + "\",\"success\":true}");
            }
        }
        /// <summary>
        /// 根据ID删除基站信息
        /// </summary>
        /// <returns></returns>
        public ActionResult DelLocaInfo()
        {
            string LocaId = Request["LocaId"];
            int Code = 0;
            string msg = "";
            using (CYOADBEntities Entities = new CYOADBEntities())
            {
                //获取基站和设备的关系
                List<string> DeviceIds = Entities.DevProRelation_Tab.Where(i => i.LocaId == LocaId).Select(i => i.DeviceId).ToList();
                string strDeviceIds = "";
                foreach (string DeviceId in DeviceIds)
                {
                    strDeviceIds += DeviceId + ",";
                }
                //获取基站绑定的设备出库信息
                int intDevice = Entities.DevInfo_Tab.Where(i => strDeviceIds.Contains(i.DeviceId) && i.State == 1).Count();
                if (intDevice > 0)
                {
                    Code = -1;
                    msg = "请先删除设备与基站的关系或确认该基站下所有设备为报废状态后，再删除该基站！";
                }
                LocaInfo_Tab lmt = Entities.LocaInfo_Tab.Where(i => i.LocaId == LocaId).FirstOrDefault();
                if (lmt != null)
                {
                    Entities.LocaInfo_Tab.Add(lmt);
                    Entities.Entry<LocaInfo_Tab>(lmt).State = System.Data.Entity.EntityState.Deleted;
                    Code = Entities.SaveChanges();
                    //获取设备出库信息表中有基站信息的出库信息
                    //DevProRelation_Tab dprt = Entities.DevProRelation_Tab.Where(i => i.LocaId == LocaId).FirstOrDefault();
                    //if (dprt != null)
                    //{
                    //    dprt.LocaId = null;
                    //    Entities.DevProRelation_Tab.Add(dprt);
                    //    Entities.Entry<DevProRelation_Tab>(dprt).State = System.Data.Entity.EntityState.Modified;
                    //    Entities.SaveChanges();
                    //}
                    List<DevProRelation_Tab> lists = Entities.DevProRelation_Tab.Where(i => i.LocaId == LocaId).ToList();
                    if (lists != null && lists.Count > 0)
                    {
                        foreach (DevProRelation_Tab DevProRelationTab in lists)
                        {
                            DevProRelationTab.LocaId = null;
                            Entities.DevProRelation_Tab.Add(DevProRelationTab);
                            Entities.Entry<DevProRelation_Tab>(DevProRelationTab).State = System.Data.Entity.EntityState.Modified;
                        }
                    }
                    List<LocaManager_Tab> list = Entities.LocaManager_Tab.Where(i => i.LocaId == LocaId).ToList();
                    if (list.Count > 1)
                    {
                        foreach (LocaManager_Tab LocaManagerTab in list)
                        {
                            Entities.LocaManager_Tab.Add(LocaManagerTab);
                            Entities.Entry<LocaManager_Tab>(LocaManagerTab).State = System.Data.Entity.EntityState.Deleted;
                        }
                        Entities.SaveChanges();
                    }
                    new DocumentController().DelDocumentByID(LocaId);
                    

                    Entities.SaveChanges();
                }
                else
                {
                    Code = -1;
                    msg = "未查询到信息，无法删除";
                }
            }
            if (Code > 0)
            {
                return Content("{\"msg\":\"删除成功！\",\"success\":true}");
            }
            else
            {
                return Content("{\"msg\":\"删除失败！" + msg + "\",\"success\":false}");
            }
        }
    }
}
